package com.java.service.impl;

import com.java.entity.Blog;
import com.java.mapper.BlogMapper;
import com.java.service.BlogService;
import com.java.utils.DateUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 博客Service接口
 * @author Administrator
 *
 */
@Service("blogService")
public class BlogServiceImpl implements BlogService {

    @Resource
    private BlogMapper blogMapper;

    @Override
    public List<Blog> getBlog() {
        List<Blog> blogList = blogMapper.getBlog();
        blogList.forEach(blog -> {
            String dateString = DateUtil.getDateString( blog.getReleaseDate(),"yyyy年MM月");
            blog.setReleaseDateStr(dateString);
        });
        Map<String,List<Blog>> map = blogList.stream().collect(Collectors.groupingBy(Blog::getReleaseDateStr));
        List<Blog> blogListResult = new ArrayList<>();
        //遍历分组后集合进行封装
        map.forEach((k,v)->{
            Blog blog = new Blog();
            blog.setReleaseDateStr(k);
            blog.setBlogCount(v.size());
            blogListResult.add(blog);
        });
        List<Blog> blogListResult2 = blogListResult;
        blogListResult2 = blogListResult2.stream().sorted(Comparator.comparing(Blog::getReleaseDateStr)).collect(Collectors.toList());
        return blogListResult2;
    }

    @Override
    public List<Blog> list(Map<String, Object> map) {
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        List<Blog> blogList = blogMapper.list(map);
        blogList.stream().sorted((a,b)->{
            try {
                return  dateFormat.parse(simpleDateFormat.format(b.getReleaseDate())).compareTo(dateFormat.parse(simpleDateFormat.format(a.getReleaseDate())));
            }catch (Exception e){
                e.printStackTrace();
            }
            return 1;
        }).collect(Collectors.toList());
        return blogList;
    }

    @Override
    public Long getTotal(Map<String, Object> map) {
        return blogMapper.getTotal(map);
    }

    @Override
    public Blog getBlogById(Integer id) {
        return blogMapper.getBlogById(id);
    }

    @Override
    public Integer updateChick(Blog blog) {
        return blogMapper.updateChick(blog);
    }

    @Override
    public Blog getLastBlog(Integer id) {
        return blogMapper.getLastBlog(id);
    }

    @Override
    public Blog getNextBlog(Integer id) {
        return blogMapper.getNextBlog(id);
    }
}
